<template>
  <div class="app-container">
    <div>
      <el-form
        id="app"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldpassword">
          <el-input
            v-model="form.oldpassword"
            class="input-reader-name"
            type="password"
            show-password
            auto-complete="off"
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item
          label="新密码"
          prop="password"
        >
          <el-input
            v-model="form.password"
            class="input-reader-name"
            type="password"
            show-password
            auto-complete="off"
            placeholder="请设置新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="repassword">
          <el-input
            v-model="form.repassword"
            class="input-reader-name"
            type="password"
            show-password
            auto-complete="off"
            placeholder="请确认新密码"
          />
        </el-form-item>
      </el-form>
    </div>
    <br>
    <div style="text-align: center">
      <el-button type="success" @click="onSubmit">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPassword, updatePassword } from '@/api/user'
import { validPassword } from '@/utils/validate'

export default {
  name: 'Reset',
  data() {
    const validateOldPassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('请输入正确的密码，不少于6个字符'))
      } else {
        callback()
      }
    }

    const validateNewPassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('请重新输入密码，不少于6个字符'))
      } else {
        if (value === this.form.oldpassword) {
          callback(new Error('新密码不能与旧密码相同，请重新输入'))
        } else {
          callback()
        }
      }
    }

    const validateNewPassword2 = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('请重新输入密码，不少于6个字符'))
      } else {
        if (value === this.form.password) {
          callback()
        } else {
          callback(new Error('新密码与确认密码不一致，请重新输入'))
        }
      }
    }

    return {
      form: {
        username: '',
        oldpassword: '',
        password: '',
        repassword: ''
      },

      // 表单校验
      rules: {
        oldpassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { validator: validateOldPassword, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请设置新密码', trigger: 'blur' },
          { validator: validateNewPassword, trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateNewPassword2, trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    /** 提交按钮 */
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          var username = window.localStorage.getItem('account')
          this.form.username = username

          const Base64 = require('js-base64').Base64
          var params = {
            'username': this.form['username'],
            'oldpassword': Base64.encode(this.form['oldpassword']),
            'password': Base64.encode(this.form['password']),
            'repassword': Base64.encode(this.form['repassword'])
          }
          var param = { 'username': username }
          getPassword(param).then((res) => {
            if (res.data === params['oldpassword']) {
              updatePassword(params).then((response) => {
                this.$router.replace(`/`)
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
              })
            } else {
              this.$message({
                type: 'error',
                message: '旧密码不正确，请重新输入'
              })
            }
          })
        } else {
          this.$message.error(`填写信息不正确，请检查`)
          return false
        }
      })
    },
    onCancel() {
      this.$confirm('此操作将退出编辑, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.replace(`/`)
        this.$message({
          type: 'success',
          message: '退出成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">

.input-reader-name {
  width: 40%;
}

</style>

